package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type messageRecord struct {
	iMessageRecord store.IMessageRecord
}

var MessageRecord = &messageRecord{
	iMessageRecord: postgres.MessageRecord,
}

func (a *messageRecord) init() func() {
	return func() {}
}

func (a *messageRecord) onEvent(*event.Data) {}

// Create 创建
func (a *messageRecord) Create(ctx context.Context, in *model.MessageRecordCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	in.UserId, _ = auth.ContextUserID(ctx)

	// 构建创建现场数据
	c := buildMessageRecord(in)
	_, err = a.iMessageRecord.Create(ctx, c)
	return err
}

// Update 更新
func (a *messageRecord) Update(ctx context.Context, in *model.MessageRecordUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.MsgId != nil {
		dict["msg_id"] = in.MsgId
	}

	if in.Success != nil {
		dict["success"] = in.Success
	}

	// do other update here
	return a.iMessageRecord.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *messageRecord) Delete(ctx context.Context, in *model.MessageRecordDeleteRequest) error {
	return a.iMessageRecord.Delete(ctx, in.Id)
}

// List 列表查询
func (a *messageRecord) List(ctx context.Context, in *model.MessageRecordListRequest) (*model.MessageRecordListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.MessageRecord
		out   = &model.MessageRecordListResponse{}
	)

	if total, list, err = a.iMessageRecord.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.MessageRecordsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *messageRecord) Find(ctx context.Context, in *model.MessageRecordInfoRequest) (*model.MessageRecordInfo, error) {
	var (
		err  error
		data *entity.MessageRecord
		out  = &model.MessageRecordInfo{}
	)

	if data, err = a.iMessageRecord.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.MessageRecordEntityToDto(data)
	return out, nil
}

// buildMessageRecord 构建创建数据现场
func buildMessageRecord(in *model.MessageRecordCreateRequest) *entity.MessageRecord {
	// todo: check the entity is required
	return &entity.MessageRecord{

		UserId: in.UserId,

		MsgId: in.MsgId,

		Success: in.Success,

		CreatedAt: time.Now().Unix(),
	}
}
